package com.budwk.app.sqfwV2.service.entrepreneurShipHouse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.component.DictComponent;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.result.GeneratorPdfWordResult;
import com.budwk.app.sqfwV2.component.EntrepreneurShipHouseComponent;
import com.budwk.app.sqfwV2.dto.dto.EntrepreneurShipHouseParamDTO;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.dto.vo.JobPersonInfoVo;
import com.budwk.app.sqfwV2.enums.EntrepreneurHouseFileEnum;
import com.budwk.app.sqfwV2.generator.entrepreneurShipHouse.EntrepreneurShipPictureGenerator;
import com.budwk.app.sqfwV2.generator.entrepreneurShipHouse.HouseholdSurveyFormDoc;
import com.budwk.app.sqfwV2.service.AssistanceSummaryDraftService;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.vo.SysDictVO;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.IocBean;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-04-26
 *
 * 创业实体入户 EntrepreneurShipHouse
 */
@IocBean
@Slf4j
public class EntrepreneurShipHousePdfService extends CompleteFlowCommonPdfService{

    @Override
    public void createPdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        super.createPdfAndMsg(paramForController);
    }


    @Override
    public GeneratorPdfWordResult createPdfSync(CompleteFlowPdfParamForController paramForController) {
        return super.createPdfSync(paramForController);
    }

    /**
     * 获取用户自定义字段 代码生成器已经自动填充
     * 无需特殊修改
     *
     * @param paramData json字符串
     * @return 结果
     */
    @Override
    protected AbstractCustomerPdfCreateField getCustomerPdfField(String paramData) {
        return JSONObject.parseObject(paramData, EntrepreneurShipHouseParamDTO.class);
    }

    /**
    * 允许用户自定义填充在创建pdf时所提供的数据
    *
    * @param pdfGenerateParam 创建pdf所提供的数据
    */
    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {

    }

    private void checkParam(Sqfw_formSummary_new formSummary) {
        if (formSummary == null) {
            throw new AppException("请求参数为空！");
        }
        if (StringUtils.isEmpty(formSummary.getParamData())) {
            throw new AppException("请求参数paramData为空！");
        }
    }


    @Override
    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {
        // 参数校验
        checkParam(formSummary);
        // 数据准备
        EntrepreneurShipHouseParamDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), EntrepreneurShipHouseParamDTO.class);
        // 带动就业人员信息
        buildJobPersonInfo(pdfDTO);
        // 计算所属产业
        pdfDTO.setBelongingIndustry(getBelongingIndustry(pdfDTO));
        // 计算年龄
        Integer age = EntrepreneurShipHouseComponent.calAge(pdfDTO.getCorporateIDNumber(), pdfDTO.getAge());
        if (age != null) {
            pdfDTO.setAge(age);
        }
        Integer gender = EntrepreneurShipHouseComponent.calGender(pdfDTO.getCorporateIDNumber(), pdfDTO.getGender());
        if (gender != null) {
            pdfDTO.setGender(gender);
        }
        EntrepreneurShipHouseParamDTO f = StrUtil.serializerData(EntrepreneurShipHouseParamDTO.class, pdfDTO);
        formSummary.setParamData(JSONObject.toJSONString(f));
        // 入库商铺
        insertShop(formSummary);
    }

    private void buildJobPersonInfo(EntrepreneurShipHouseParamDTO pdfDTO) {
        List<JobPersonInfoVo> jobPersonInfo = pdfDTO.getJobPersonInfo();
        if (CollectionUtil.isEmpty(jobPersonInfo)) {
            pdfDTO.setJobNumber(0);
            return;
        }
        pdfDTO.setJobNumber(jobPersonInfo.size());
        for (JobPersonInfoVo jobPersonInfoVo : jobPersonInfo) {
            String idcard = jobPersonInfoVo.getIdcard();
            Integer age = EntrepreneurShipHouseComponent.calAge(idcard, jobPersonInfoVo.getAge());
            if (age != null) {
                jobPersonInfoVo.setAge(age);
            }
            Integer gender = EntrepreneurShipHouseComponent.calGender(idcard, jobPersonInfoVo.getGender());
            if (gender != null) {
                jobPersonInfoVo.setGender(gender);
            }
        }
    }


    @Override
    protected void afterInsertForSummary(Sqfw_formSummary_new formSummary) {
        // 数据准备
        EntrepreneurShipHouseParamDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), EntrepreneurShipHouseParamDTO.class);
        // 删除草稿箱数据
        String draftId = pdfDTO.getDraftId();
        AssistanceSummaryDraftService draftService = NutzIocUtils.getBean(AssistanceSummaryDraftService.class);
        if (StringUtils.isNotEmpty(draftId)) {
            draftService.deleteData(draftId);
        }
    }

    private void insertShop(Sqfw_formSummary_new formSummary) {
        // 如果是小型是是的话
        EntrepreneurShipHouseParamDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), EntrepreneurShipHouseParamDTO.class);
        ShopsBaseInfoService shopsBaseInfoService = NutzIocUtils.getBean(ShopsBaseInfoService.class);
        SqfwShopsBaseInfo shopsBaseInfo = JSONObject.toJavaObject(JSONObject.parseObject(formSummary.getParamData()), SqfwShopsBaseInfo.class);
        shopsBaseInfo.setPlaceName(pdfDTO.getPlaceName())
                .setMainBusinessScope(pdfDTO.getMainBusinessScope())
                .setSocialCreditCode(pdfDTO.getSocialCreditCode())
                .setAddress(pdfDTO.getAddress())
                .setOperator(pdfDTO.getOperator())
                .setShopStatus(SqfwFormSummaryFieldEnum.check_status_init.getCode())
                .setInspectionSituation(SqfwFormSummaryFieldEnum.CHECK_SITUATION_NO.getCode())
                .setServiceType(SupportBusinessTypeEnum.ENTERPRENEURAL.getCode())
                .setFillDate(pdfDTO.getFillDate())
                .setOperatorTelephone(pdfDTO.getOperatorTelephone());
        SqfwShopsBaseInfo s = shopsBaseInfoService.insertOrUpdateData(shopsBaseInfo, formSummary);

        String detailAddress = String.format("%s%s%s%s%s%s%s", formSummary.getProvince(), formSummary.getCity(), formSummary.getDistrict(),
                formSummary.getCounty(), formSummary.getCommunity(), shopsBaseInfo.getAddress(), shopsBaseInfo.getPlaceName());
        formSummary.setShopsBaseInfoId(s.getId())
                .setInspectionSituation(SqfwFormSummaryFieldEnum.CHECK_SITUATION_NO.getCode())
                .setDetailAddress(detailAddress);
    }

    private String getBelongingIndustry(EntrepreneurShipHouseParamDTO pdfDTO) {
        SysDictService dictService = NutzIocUtils.getBean(SysDictService.class);
        // 第一产业
        List<SysDictVO> dictVOS = dictService.listDictByCode(DictConstants.BELONG_INDUS_ONE);
        Optional<SysDictVO> first = dictVOS.stream().filter(e -> e.getCode().equals(pdfDTO.getIndustrySector())).findFirst();
        if (first.isPresent()) {
            return DictConstants.BELONG_INDUS_ONE;
        }
        List<SysDictVO> dictVOS2 = dictService.listDictByCode(DictConstants.BELONG_INDUS_TWO);
        Optional<SysDictVO> first2 = dictVOS2.stream().filter(e -> e.getCode().equals(pdfDTO.getIndustrySector())).findFirst();
        if (first2.isPresent()) {
            return DictConstants.BELONG_INDUS_TWO;
        }
        List<SysDictVO> dictVOS3 = dictService.listDictByCode(DictConstants.BELONG_INDUS_THREE);
        Optional<SysDictVO> first3 = dictVOS3.stream().filter(e -> e.getCode().equals(pdfDTO.getIndustrySector())).findFirst();
        if (first3.isPresent()) {
            return DictConstants.BELONG_INDUS_THREE;
        }
        // 默认返回第三产业
        return DictConstants.BELONG_INDUS_THREE;
    }

    /**
     * 在这里设置生成pdf的所有generator
     *
     * @param pdfGenerateParam 创建pdf的参数
     * @return 生成pdf的generator合集
     */
    @Override
    protected List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam) {
        List<BasePdfGenerator> generatorList = Lists.newArrayList();
        // 在这里添加自己的generator
        // 例如 generatorList.add(new RefuseClassifyPdfGenerator());
         generatorList.add(new HouseholdSurveyFormDoc());
         generatorList.add(new EntrepreneurShipPictureGenerator());
        return generatorList;
    }

    /**
     * 重新创建pdf之前可以自定义进行操作
     *
     */
    @Override
    protected void beforeReGenPdf(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummaryNew, Map<String, Object> businessDataMap) {
        String paramData = formSummaryNew.getParamData();
        beforeInsertForSummary(formSummaryNew);
        String paramData1 = formSummaryNew.getParamData();
        if (!paramData.equals(paramData1)) {
            // 修改数据
            SqfwFormsummaryNewService sqfwFormsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
            sqfwFormsummaryNewService.updateIgnoreNull(formSummaryNew);
        }
    }

    /**
    * 用户自定义下载pdf文件的名称
    *
    * @param pdfGenerateParam 创建pdf所提供的参数
    * @return 结果
    */
    @Override
    protected String getDownloadFileName(PdfGenerateParam pdfGenerateParam) {
        String fileName = DictComponent.getDictName(EntrepreneurHouseFileEnum.ONE_PDF.getCode(), null);
        EntrepreneurShipHouseParamDTO fieldDTO = (EntrepreneurShipHouseParamDTO) pdfGenerateParam.getAbstractCustomerPdfCreateField();
        return String.format("%s%s%s%s%s", fileName, "-",fieldDTO.getPlaceName(), "-",LocalDateTimeUtil.format(LocalDate.now(), DatePattern.PURE_DATE_PATTERN));
    }

    /**
    * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
    *
    * @return 返回数据
    */
    @Override
    public String getSummaryType() {
        return SupportBusinessTypeEnum.ENTERPRENEURAL.getName();
    }
}
